#!/usr/bin/env python3
"""
设备管理系统启动脚本
支持多环境配置管理
"""

import sys
import os
import argparse
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# 添加项目路径
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
    sys.path.insert(0, current_dir)

# 导入配置管理
from app.core.config import get_settings
from app.core.config_manager import config_manager, print_config_info

def create_app():
    """创建FastAPI应用"""
    # 获取当前环境配置
    settings = get_settings()
    
    # 创建FastAPI实例，使用配置中的参数
    app = FastAPI(
        title=settings.app_name,
        description=f"基于FastAPI的设备管理系统 - {settings.environment.upper()}环境",
        version=getattr(settings, 'app_version', '1.0.0'),
        docs_url=settings.docs_url,
        redoc_url=settings.redoc_url,
        openapi_url=settings.openapi_url,
        debug=settings.debug
    )

    # CORS中间件 - 使用配置中的CORS设置
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.cors_origins,
        allow_credentials=settings.cors_allow_credentials,
        allow_methods=settings.cors_allow_methods,
        allow_headers=settings.cors_allow_headers,
    )

    # 手动注册基本路由
    @app.get("/")
    async def root():
        return {
            "message": f"{settings.app_name} API",
            "environment": settings.environment,
            "version": getattr(settings, 'app_version', '1.0.0'),
            "status": "运行中",
            "docs_url": settings.docs_url,
            "redoc_url": settings.redoc_url
        }

    @app.get(settings.health_check_path)
    async def health_check():
        return {
            "status": "healthy",
            "environment": settings.environment,
            "database": "connected" if settings.database_url else "not configured",
            "redis": "connected" if settings.redis_url else "not configured",
            "scheduler": "enabled" if settings.scheduler_enabled else "disabled"
        }

    # 尝试注册业务路由
    imported_modules = []
    
    # 注册认证路由
    try:
        from app.api.v1 import auth
        app.include_router(auth.router, prefix=settings.api_v1_prefix, tags=["认证"])
        imported_modules.append("auth")
        print("✅ 认证路由注册成功")
    except Exception as e:
        print(f"❌ 认证路由失败: {e}")

    # 注册设备路由
    try:
        from app.api.v1 import devices
        app.include_router(devices.router, prefix=settings.api_v1_prefix, tags=["设备管理"])
        imported_modules.append("devices")
        print("✅ 设备路由注册成功")
    except Exception as e:
        print(f"❌ 设备路由失败: {e}")

    # 注册维护记录路由
    try:
        from app.api.v1 import maintenance_records
        app.include_router(maintenance_records.router, prefix=settings.api_v1_prefix, tags=["维护记录"])
        imported_modules.append("maintenance_records")
        print("✅ 维护记录路由注册成功")
    except Exception as e:
        print(f"❌ 维护记录路由失败: {e}")
        if settings.debug:
            import traceback
            traceback.print_exc()

    # 注册维护计划路由
    try:
        from app.api.v1 import maintenance_plans
        app.include_router(maintenance_plans.router, prefix=settings.api_v1_prefix, tags=["维护计划"])
        imported_modules.append("maintenance_plans")
        print("✅ 维护计划路由注册成功")
    except Exception as e:
        print(f"❌ 维护计划路由失败: {e}")
        if settings.debug:
            import traceback
            traceback.print_exc()
    
    # 注册定时任务路由
    try:
        from app.api.v1 import scheduled_jobs
        app.include_router(scheduled_jobs.router, prefix=settings.api_v1_prefix, tags=["定时任务"])
        imported_modules.append("scheduled_jobs")
        print("✅ 定时任务路由注册成功")
    except Exception as e:
        print(f"❌ 定时任务路由失败: {e}")
        if settings.debug:
            import traceback
            traceback.print_exc()
    
    # 如果启用了监控，注册监控路由
    if settings.metrics_enabled:
        try:
            # TODO: 添加Prometheus监控路由
            print("📊 监控功能已启用")
        except Exception as e:
            print(f"❌ 监控路由失败: {e}")

    print(f"\n📊 注册结果:")
    print(f"   成功模块: {imported_modules}")
    print(f"   总路由数: {len(app.routes)}")
    
    return app

def main():
    """主函数"""
    # 解析命令行参数
    parser = argparse.ArgumentParser(description="设备管理系统启动脚本")
    parser.add_argument(
        "--env", 
        choices=["development", "testing", "staging", "production"],
        help="指定运行环境"
    )
    parser.add_argument(
        "--host",
        default=None,
        help="指定服务器地址"
    )
    parser.add_argument(
        "--port",
        type=int,
        default=None,
        help="指定服务器端口"
    )
    parser.add_argument(
        "--reload",
        action="store_true",
        help="启用热重载（仅开发环境）"
    )
    parser.add_argument(
        "--log-level",
        choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
        help="指定日志级别"
    )
    parser.add_argument(
        "--config-info",
        action="store_true",
        help="显示配置信息并退出"
    )
    
    args = parser.parse_args()
    
    # 设置环境
    if args.env:
        config_manager.switch_environment(args.env)
    
    # 显示配置信息
    if args.config_info:
        print_config_info()
        return
    
    print("🚀 启动设备管理系统...")
    
    # 显示当前配置信息
    print_config_info()
    
    # 获取配置
    settings = get_settings()
    
    # 创建应用
    app = create_app()
    
    # 确定启动参数
    host = args.host or settings.host
    port = args.port or settings.port
    log_level = (args.log_level or settings.log_level).lower()
    
    # 热重载设置
    reload = args.reload and settings.environment == "development"
    if args.reload and settings.environment != "development":
        print("⚠️  警告：热重载仅在开发环境中启用")
    
    print(f"\n🌐 服务信息:")
    print(f"   环境: {settings.environment.upper()}")
    print(f"   地址: http://{host}:{port}")
    
    if settings.docs_url:
        print(f"   API文档: http://{host}:{port}{settings.docs_url}")
    if settings.redoc_url:
        print(f"   Redoc文档: http://{host}:{port}{settings.redoc_url}")
    
    print(f"   健康检查: http://{host}:{port}{settings.health_check_path}")
    print(f"   日志级别: {log_level.upper()}")
    print(f"   热重载: {'启用' if reload else '禁用'}")
    
    if settings.metrics_enabled:
        print(f"   监控指标: http://{host}:{port}{settings.metrics_path}")
    
    print(f"\n🚀 启动服务器...\n")
    
    try:
        uvicorn.run(
            "start_server:create_app" if reload else app,
            host=host,
            port=port,
            reload=reload,
            log_level=log_level,
            factory=reload,
            access_log=settings.debug
        )
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")
    except Exception as e:
        print(f"❌ 服务器启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()